package com.arcsoft.commonbase.widgets

import android.content.Context
import android.graphics.*
import android.graphics.drawable.InsetDrawable
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.arcsoft.commonbase.R

class ShadowRelativeLayout: RelativeLayout {

    /**
     * 阴影的颜色
     */
    private var shadowColor = Color.argb(90, 0, 0, 0)

    /**
     * 高斯模糊的模糊半径,值越大越模糊，越小越清晰,
     */
    private var shadowBlur = 30f

    /**
     * 阴影的圆角
     */
    private var shadowRadius = 0f

    /**
     * 阴影的偏移
     */
    private var shadowDx = 0f
    private var shadowDy = 0f

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)


    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        dealAttrs(context, attrs)
        setPaint()
    }

    private fun dealAttrs(context: Context, attrs: AttributeSet?) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShadowRelativeLayout)
        shadowColor = typedArray.getColor(R.styleable.ShadowRelativeLayout_shadow_color, shadowColor)
        shadowRadius = typedArray.getDimension(R.styleable.ShadowRelativeLayout_shadow_radius, shadowRadius)
        shadowBlur = typedArray.getDimension(R.styleable.ShadowRelativeLayout_shadow_blur, shadowBlur)
        shadowDx = typedArray.getDimension(R.styleable.ShadowRelativeLayout_shadow_dx, shadowDx)
        shadowDy = typedArray.getDimension(R.styleable.ShadowRelativeLayout_shadow_dy, shadowDy)
        typedArray.recycle()
    }

    private fun setPaint() {
        setLayerType(LAYER_TYPE_SOFTWARE, null) // 关闭硬件加速,阴影才会绘制
        mPaint.isAntiAlias = true
        mPaint.color = shadowColor
        mPaint.maskFilter = BlurMaskFilter(shadowBlur, BlurMaskFilter.Blur.NORMAL)
    }

    override fun draw(canvas: Canvas?) {
        setInsetBackground()
        canvas?.drawRoundRect(getRectF(), shadowRadius, shadowRadius, mPaint)
        super.draw(canvas)
    }

    private fun setInsetBackground() {
        if (background == null || background is InsetDrawable) {
            return
        }

        val drawable = InsetDrawable(background, paddingLeft, paddingTop, paddingRight, paddingBottom)
        background = drawable
    }

    private fun getRectF():RectF {
        return RectF(paddingLeft + shadowDx, paddingTop + shadowDy, width - paddingRight + shadowDx, height - paddingBottom + shadowDy)
    }

    override fun isOpaque(): Boolean {
        //纯色或图片做背景时,draw之前会有黑底色，
        return false
    }
}